<?php

namespace Home\Controller;

use Think\Controller;

class LoginController extends Controller
{
    public function login_no()
    {
        if ($_SESSION['phone'] && $_SESSION['id']) {
            $info = D('Admin');
            $id = $info->where(['phone' => $_SESSION['phone'], 'id' => $_SESSION['id']])->getfield('id');
            if (!empty($id)) {
                $this->redirect('Index/index');
            }
        }
    }

    public function login()
    {
        $this->login_no();
        $this->display();
    }

    public function logino()
    {
        $this->login_no();
        $this->display();
    }

    /**
     * 用户登录验证
     */
    public function get_login()
    {
        if (!empty($_POST)){
//            $this->ajax('1002', 'IP非法! 请联系管理员', 'error');
//            die;
            $info = D('Admin');
            $phone = I('phone');
            $pwd = set_pwd(I('pwd'),$phone);
//            var_dump($pwd);
            $res = $info->check_login($phone, $pwd);

//            var_dump($res);
//            die;

            //IP限制
            if($phone!='13758792879'){
                $post_data = array(
                    'from' => '客服系统'
                );
                $ret =$this->send_post('http://adm.jyyjrfw.com/External/external_get_allow_ip', $post_data);
                $json = json_decode($ret);
                $ip_arr=$json->result;
                $ip = getIP();
                if (!in_array($ip, $ip_arr)){
                    $this->ajax('1002', 'IP非法! 请联系管理员', 'error');
                    die;
                }
            }

//            var_dump($res);
            if($res['login_sys']!='1'){
                $this->ajax('1002', 'sorry你没有权限登录此系统', 'error');
                die;
            }


            if ($res){
                session('id', $res['id']);
                session('phone', $res['phone']);
                session('name', $res['name']);
                session('role_id', $res['role_id']);
                session('part_id', $res['part_id']);
                session('out_kf_id', $res['out_kf_id']);
                session('agent', $res['agent']);
                session('login_time', date('Y-m-d H:i:s', time()));
                add_log($_SESSION['id']);
                $this->ajax('1001', '登录成功');
            } else {
                $this->ajax('1002', '用户名或者密码错误', 'error');
            }
        }
    }
    /**
     * 用户密码修改
     */
    public function modify()
    {
        if (empty($_SESSION['id'])) {
            $this->redirect('Login/login');
        }
        $this->display();
    }

    /**
     * 修改密码操作
     */
    public function modify_pwd()
    {
        if (empty($_SESSION['id'])) $this->redirect('Login/login');
        if (!empty($_POST)) {
            $info = D('Admin');
            if (strlen(I('new_pwd')) < 6) {
                $this->ajax('1002', '密码长度不能小于6位', 'error');
            }
//            $old_pwd = md5(I('old_pwd') . 'dxd' . $_SESSION['phone']);
//            $new_pwd = md5(I('new_pwd') . 'dxd' . $_SESSION['phone']);
            $old_pwd = set_pwd(I('old_pwd'), $_SESSION['phone']);
            $new_pwd = set_pwd(I('new_pwd'), $_SESSION['phone']);
            $check = $info->check_modify_pwd($_SESSION['phone'], $old_pwd, $new_pwd);
            switch ($check) {
                case 1001:
                    $res = $info->WHERE(['pwd' => $old_pwd, 'phone' => $_SESSION['phone']])->setField('pwd', $new_pwd);
                    if ($res !== false) {
                        $content = '修改登录密码';
                        addlog($check['id'], $content);
                        $str = array('aid' => $_SESSION['id'], 'content' => ' 修改密码', 'ctime' => time());
                        $record = M('admin_log', '', 'KEFU')->add($str);
                        session(null);
                        $this->ajax('1001', '修改成功');
                    } else {
                        $this->ajax('1002', '修改失败', 'error');
                    };
                    break;
                case 1002:
                    $this->ajax('1002', '原始密码错误', 'error');
                    break;
                case 1003:
                    $this->ajax('1002', '新密码不能和原始密码相同', 'error');
                    break;
                case 1004:
                    $this->ajax('1002', '用户不存在', 'error');
                    break;
                default:
                    $this->ajax('1002', '系统错误', 'error');
            }
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        $str = array('aid' => $_SESSION['id'], 'content' => '退出登录', 'ctime' => time());
        $record = M('admin_log', '', 'KEFU')->add($str);

        session(null);
        $this->redirect('/login');
    }

    /**
     * @param $code 错误码 1001成功 1002失败
     * @param $result 详细信息
     * @param string $r 为error的时候表示返回错误信息
     * @return bool
     */

    public function ajax($code, $result, $r = '')
    {
        if (empty($r)) {
            $this->ajaxReturn(['code' => $code, 'result' => $result]);
        } else {
            $this->ajaxReturn(['code' => $code, 'result' => $result]);
            return false;
        }
    }

    /**
     * 发送post请求
     * @param string $url 请求地址
     * @param array $post_data post键值对数据
     * @return string
     */
    public function send_post($url, $post_data)
    {

        $postdata = http_build_query($post_data);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }
    public function _empty()
    {
        $this->redirect('Alerterror/error404');
    }
}